<template>
  <div>
      <p class="text-lg font-bold">采购模板</p>
      <a-row :gutter="[32,8]">
        <a-col :span="12">
            <vxe-button status="primary" icon="vxe-icon-add" @click="addEvent"
              >新增模板</vxe-button
            >
            <vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvent">
            <template #user="{ row }">
            {{ row.user?row.user.user_name:'' }}
          </template>
              <template #action="{ row }">
              
                <vxe-button
                  status="primary"
                  content="查看"
                  @click="showRow(row)"
                ></vxe-button>

                <vxe-button
                  status="error"
                  content="删除"
                  @click="remove(row)"
                ></vxe-button>
              </template>
            </vxe-grid>
          
        </a-col>
        <a-col :span="12"> 
        <p class="text-lg font-bold">货单预览</p>
        <!--              table-->
            <vxe-table
              border
              show-overflow
              show-footer
              keep-source
              :is-hover="true"
              ref="xTable"
              :column-config="{ resizable: true }"
              :data="detailData"
            >
              <vxe-column field="id" title="货品ID" sortable>
                <template #default="{ row }">
                  {{ row.product.id}}
                </template>
              </vxe-column>
              <vxe-column field="name" title="货品名称" sortable>
                <template #default="{ row }">
                  {{ row.product.name }}
                </template>
              </vxe-column>
            </vxe-table>
            <!--              table-->
        </a-col>
        
        
        
          <DraggableModal
            v-model:open="showEditPopup"
            :width="'1400px'"
            title="模板管理"
            :keyboard="false"
            :footer="false"
          >
            <a-form :model="pTemplateform" :layout="'vertical'" ref="formRef">
              <a-row>
                <a-col :span="12">
                  <a-form-item
                    label="名称"
                    name="name"
                    style="width: 400px"
                    :rules="[
                      ruleStore.getRule('name')
                        ? ruleStore.getRule('name')
                        : { required: false },
                    ]"
                  >
                    <a-input v-model:value="pTemplateform.name"> </a-input>
                  </a-form-item>
                </a-col>
              </a-row>

              <a-form-item
                label="货品"
                name="template_items"
                :rules="[
                  ruleStore.getRule('template_items')
                    ? ruleStore.getRule('template_items')
                    : { required: false },
                ]"
              >
                <a-transfer
                  v-model:target-keys="targetKeys"
                  :data-source="productList"
                  :show-search="true"
                  :filter-option="
                    (inputValue, item) => item.title.indexOf(inputValue) !== -1
                  "
                  :show-select-all="false"
                  @change="onChange"
                >
                  <template
                    #children="{
                      direction,
                      filteredItems,
                      selectedKeys,
                      disabled: listDisabled,
                      onItemSelectAll,
                      onItemSelect,
                    }"
                  >
                    <a-table
                      :row-selection="
                        getRowSelection({
                          disabled: listDisabled,
                          selectedKeys,
                          onItemSelectAll,
                          onItemSelect,
                        })
                      "
                      :columns="
                        direction === 'left' ? leftColumns : rightColumns
                      "
                      :data-source="filteredItems"
                      size="small"
                      :style="{ pointerEvents: listDisabled ? 'none' : null }"
                      :custom-row="
                        ({ key, disabled: itemDisabled }) => ({
                          onClick: () => {
                            if (itemDisabled || listDisabled) return;
                            onItemSelect(key, !selectedKeys.includes(key));
                          },
                        })
                      "
                    />
                  </template>
                </a-transfer>
              </a-form-item>
              <a-form-item>
                <a-button type="primary" style="width: 100px" @click="onSubmit"
                  >提交</a-button
                >
              </a-form-item>
            </a-form>
          </DraggableModal>
      </a-row>
  </div>
</template>

<script setup lang="ts">
import { VxeUI } from "vxe-pc-ui";
import useRuleStore from "@/store/modules/rule";
import XEUtils from "xe-utils";
import { message } from "ant-design-vue";
import Api from "@/api/backend/api";
const ruleStore = useRuleStore();
const { gridOptions } = usePurchaseTemplate();

const formRef = ref();
const showEditPopup = ref(false);
const loading = ref(false);
const selectRow = ref<RowVO>();
const defaultData: RowVO = {
  id: null,
  name: "",
};
const pTemplateform = ref({
  id: null,
  name: "",
  template_items: [],
});

const xGrid = ref();
const gridEvent: VxeGridListeners<RowVO> = {
  proxyQuery() {
    console.log("数据代理查询事件");
    const grid = xGrid.value;
    // 获取表格中的数据
    // const data = grid.getTableData().fullData;
    // console.log(data);
  },
  proxyDelete() {
    console.log("数据代理删除事件");
  },
  proxySave() {
    console.log("数据代理保存事件");
  },
};

const remove = (row: any) => {
  console.log(row);
};
const addEvent = () => {
  showEditPopup.value = true;
};
const onSubmit = async () => {
  if (pTemplateform.value.template_items.length == 0) {
    return message.error("请选择商品");
  }
  try {
    //先清空一下验证
    formRef.value.clearValidate();
    await Api.purchasetemplateController.store(pTemplateform.value);
    
  } catch (error) {
    console.log(error);
    formRef.value.validate();
  }
};
const productList = ref([]);
const productData = ref([]);
const init = async () => {
  const data = await Api.productController.list();
  productData.value = data;
  productList.value = data.map((item) => {
    return {
      key: item.id.toString(), // 确保 key 是字符串类型
      title: item.name,
      description: `【规】${item.spec},【单】${item.unit}，【价】${item.price}`,
    };
  });
};
init();
//穿梭框
const originTargetKeys = productList.value
  .filter((item) => +item.key % 3 > 1)
  .map((item) => item.key);

const leftTableColumns = [
  {
    dataIndex: "title",
    title: "品名",
  },
  {
    dataIndex: "description",
    title: "描述",
  },
];
const rightTableColumns = [
  {
    dataIndex: "title",
    title: "品名",
  },
  {
    dataIndex: "description",
    title: "描述",
  },
];

const targetKeys = ref<string[]>(originTargetKeys);
const disabled = ref<boolean>(false);
const showSearch = ref<boolean>(false);
const leftColumns = ref<tableColumn[]>(leftTableColumns);
const rightColumns = ref<tableColumn[]>(rightTableColumns);

const onChange = (nextTargetKeys: string[]) => {
  console.log("nextTargetKeys", nextTargetKeys);
  if (nextTargetKeys && nextTargetKeys.length > 0) {
    pTemplateform.value.template_items = productData.value
      .filter((item) => nextTargetKeys.map(Number).includes(item.id))
      .map((i) => {
        return {
          product_id: i.id,
          owner_id: i.id,
          owner_type: "purchase",
        };
      });
  }
};

const getRowSelection = ({
  disabled,
  selectedKeys,
  onItemSelectAll,
  onItemSelect,
}: Record<string, any>) => {
  return {
    getCheckboxProps: (item: Record<string, string | boolean>) => ({
      disabled: disabled || item.disabled,
    }),
    onSelectAll(
      selected: boolean,
      selectedRows: Record<string, string | boolean>[]
    ) {
      const treeSelectedKeys = selectedRows
        .filter((item) => !item.disabled)
        .map(({ key }) => key);
      onItemSelectAll(treeSelectedKeys, selected);
    },
    onSelect({ key }: Record<string, string>, selected: boolean) {
      onItemSelect(key, selected);
    },
    selectedRowKeys: selectedKeys,
  };
};

//查看模板
const showRow = (row) => {
  showPurchaseDetail(row.id);
};

//查看模板内容

const detailData=ref([])
const showPurchaseDetail=async (id)=>{
  detailData.value = await Api.purchasetemplateController.detail({
    id:id
  })
}
</script>

<style></style>
